package com.techwells.taco.widget;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.techwells.taco.networkaccessor.NetworkResponse;
import com.techwells.taco.networkservice.Field_Method_Parameter_Annotation;
import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.networkservice.ServiceResponse;
import com.techwells.taco.utils.LogUtil;
import com.techwells.taco.utils.ToastUtils;



@SuppressLint({ "HandlerLeak", "DefaultLocale" })
public class UpdateUtil {
	private int drawabledIconId;
	private Activity mainActivity;
	private Notification mNotification;
	private File mfile;
	private int lastProgress;
	public static UpdateUtil update;
	private Boolean isApkDownloading = false;
	public Handler downloadHandler = null;

	public Activity getActivity() {
		return mainActivity;
	}

	public UpdateUtil() {
		downloadHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ServiceMediator.Service_Return_Success:
					ServiceResponse<?> response = (ServiceResponse<?>) msg.obj;
					if (null != response.getResponse()) {
						finishedDownloadApk((File) response.getResponse());
					}
					break;
				default:
					ServiceResponse<?> errorResp = (ServiceResponse<?>) msg.obj;
					if (null != errorResp.getReturnDesc()) {
						validationVersionFailed((String) errorResp
								.getReturnDesc());
					}
					finishedDownloadApk(null);
					break;
				}
			}
		};
	}

	public void validationVersionFailed(String errDesc) {
		ToastUtils.show(getActivity(), errDesc);
	}

	public void setDrawabledIconId(int drawId) {
		drawabledIconId = drawId;
	}

	public void initUpdateUtil(Activity act) {
		mainActivity = act;
		mNotificationManager = (NotificationManager) mainActivity
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public Boolean isUpdating() {
		return isApkDownloading;
	}

	public void setIsUpdating(Boolean updating) {
		isApkDownloading = updating;
	}

	private AlertDialog versionUpdateDialog;
	private NotificationManager mNotificationManager;

	public AlertDialog getVersionUpdateDialog() {
		return versionUpdateDialog;
	}

	public void setFile(File file) {
		mfile = file;
	}

	public void setVersionUpdateDialog(String title, String confirmString,
			String secondString, Activity context) {
		versionUpdateDialog = alertDialog(title, confirmString, secondString,
				context);
	}

	private void install(Context ctx) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(mfile),
					"application/vnd.android.package-archive");
			ctx.startActivity(intent);
		} catch (Exception e) {

		}
	}

	@SuppressWarnings("deprecation")
	public void showNotification() {
		isApkDownloading = true;
		lastProgress = 0;
		mNotification = new Notification(drawabledIconId, "下载更新包",
				System.currentTimeMillis());
		mNotification.setLatestEventInfo(mainActivity, "更新", "正在下载更新...1%",
				makeMoodIntent(drawabledIconId));
		mNotificationManager.notify(0, mNotification);
	}

	private PendingIntent makeMoodIntent(int moodId) {
		PendingIntent contentIntent = PendingIntent.getActivity(mainActivity,
				0, new Intent(mainActivity, mainActivity.getClass()).putExtra(
						"moodimg", moodId), PendingIntent.FLAG_UPDATE_CURRENT);
		return contentIntent;
	}

	public AlertDialog getVersionUpdateAlertDialog() {
		return versionUpdateDialog;
	}

	@SuppressWarnings("deprecation")
	public void finishedDownloadApk(File file) {
		isApkDownloading = false;

		if (null != file) {
			setFile(file);
			mNotification.setLatestEventInfo(mainActivity, "更新", "下载更新包完成。",
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
			install(mainActivity);
			mNotificationManager.cancel(0);
		} else {
			mNotification.setLatestEventInfo(mainActivity, "更新", "下载更新包失败",
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("DefaultLocale")
	public void downloadProgress(float progress) {
		progress = progress < 0 ? 0 : progress;
		progress = progress > 1 ? 1 : progress;
		int pro = (int) (progress * 100);
		if (pro - lastProgress > 1) {
			lastProgress = pro;
			String str = String.format("正在下载更新...%d%%", pro);
			mNotification.setLatestEventInfo(mainActivity, "更新", str,
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
		}
	}

	public AlertDialog alertDialog(String title, String confirmString,
			String secondString, final Activity context) {
		return null;
	}

	public Handler getHandler() {
		return downloadHandler;
	}

	/**
	 * 异步下载apk包
	 * 
	 * @param url
	 * @param context
	 */
	public void downloadApkFile(final String url, final Context context) {
		// 异步完成任务
		showNotification();
		new Thread(new Runnable() {
			public void run() {
				ServiceResponse<?> response = downloadAPK(url, UpdateUtil.this,
						context);
				Message message = new Message();
				message.what = response.getReturnCode();
				message.obj = response;
				getHandler().sendMessage(message);
			}
		}).start();
	}

	/** 版本升级路径 */
	public static String getUpdatePath(Context context) {
		String path = "/update.apk";
		path = context.getFilesDir().getAbsolutePath() + path;
		return path;
	}

	@Field_Method_Parameter_Annotation(args = { "urlString", "updateUtil",
			"context" })
	public static ServiceResponse<File> downloadAPK(String urlString,
			UpdateUtil updateUtil, Context context) {
		String path = UpdateUtil.getUpdatePath(context);
		ServiceResponse<File> response = new ServiceResponse<File>();
		NetworkResponse networkResponse = httpRequestDownload(path, urlString,
				updateUtil);
		if (networkResponse.getStatusCode() == HttpURLConnection.HTTP_OK) {
			response.setReturnCode(ServiceMediator.Service_Return_Success);

			// ������������������
			String command = "chmod " + "777" + " " + path;
			Runtime runtime = Runtime.getRuntime();
			try {
				runtime.exec(command);
			} catch (IOException e) {
				e.printStackTrace();
			}
			File file = new File(path);
			response.setResponse(file);
		} else {
			response.setReturnDesc("���������������������");
			response.setReturnCode(ServiceMediator.Service_Return_Error);
		}
		return response;
	}

	/**
	 * ������������
	 * 
	 * @param urlString
	 * @return
	 */
	public static NetworkResponse httpRequestDownload(String filePath,
			String urlString, UpdateUtil updateUtil) {
		final NetworkResponse resultResponse = new NetworkResponse();
		LogUtil.e("zhangss", "Download URL:" + urlString);
		URL url;
		try {
			url = new URL(urlString);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			int total = conn.getContentLength();
			int progress = 0;
			byte[] buffer = new byte[64];
			int len;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				progress += len;
				if (null != updateUtil) {
					updateUtil.downloadProgress((progress / (float) total));
				}
			}
			bis.close();
			fos.close();
			is.close();
			conn.disconnect();
			if (progress == total) {
				resultResponse.setWithData(null, HttpURLConnection.HTTP_OK,
						null);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}
		
		return resultResponse;
	}
}
